package com.lifp.thread.juc;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

/**
 * @Description CountDownLatch 减少计数类测试
 * @Author lfp
 * @Date 2022/8/4
 * @Version 1.0
 */
public class CountDownLatchDemo {

    //场景：6个同学陆续离开教室之后，班长锁门
    public static void main(String[] args) {

        //传统线程来实现，会出现错乱：所有同学还未全部离开，班长锁门走人了
        traditionThread();

        //使用计数器来实现，保证实现业务
        //countDownLatchThread();
    }

    
    /**
    *@Description 传统多线程方式来实现
    *@Return
    */
    public static void traditionThread(){
        //创建6个线程，模拟6个同学
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " 号同学离开了教室");
            },String.valueOf(i+1)).start();
        }
        System.out.println(Thread.currentThread().getName() +" 班长锁门走人了");
    }

    
    /**
    *@Description 通过countDownLatch 来实现
    *@Return
    */
    @SneakyThrows
    public static void countDownLatchThread(){

        //1、创建CountDownLatch对象，设置初始值
        CountDownLatch countDownLatch = new CountDownLatch(6);

        //2、创建6个线程，模拟6个同学
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + " 号同学离开了教室");

                ///3、计数器 -1
                countDownLatch.countDown();
            },String.valueOf(i+1)).start();
        }

        //4、等待 （计数器为0之后，会激活此线程，从而继续向下执行）
        countDownLatch.await();

        System.out.println(Thread.currentThread().getName() +" 班长锁门走人了");
    }
}
